package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderResponse;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.order.api.ProductApi;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;


    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;


    @Autowired
    ProductApi productApi;
    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    @Transactional
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {

        String orderId = request.getOrderId();
        CancelOrderResponse response = new CancelOrderResponse();

        try {
            // 通过orderId修改order表
            Order order = new Order();
            order.setOrderId(orderId);
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setUpdateTime(new Date());
            order.setCloseTime(new Date());
            int effectRows = orderMapper.updateByPrimaryKeySelective(order);
            if (effectRows < 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }

            // 获取订单中的itemId，需要通过这个id修改库存表
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setStockCount(num.longValue());
                stock.setLockCount(-num);
                stock.setItemId(itemId);
                stockMapper.updateStock(stock);
                // TODO: 也没管限购的问题
//                orderItem.setStatus(OrderConstants.ORDER_ITEM_STATUS_RELEASED);
//                int effectRows2 = orderItemMapper.updateByPrimaryKey(orderItem);
//                if (effectRows2 < 1) {
//                    throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
//                }
            }



            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.cancelOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {

        String orderId = request.getOrderId();
        DeleteOrderResponse response = new DeleteOrderResponse();

        try {
            // 校验订单状态，从付款后到交易成功前都不能删除订单
            Order order = orderMapper.selectByPrimaryKey(orderId);
            Integer status = order.getStatus();
            if (status >= OrderConstants.ORDER_STATUS_INIT && status < OrderConstants.ORDER_STATUS_TRANSACTION_SUCCESS) {
                response.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
                response.setMsg("当前订单未完成！");
                return response;
            }

            Order order1 = new Order();
            order1.setOrderId(orderId);
            order1.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CLOSE);
            order1.setCloseTime(new Date());
            order1.setUpdateTime(new Date());
            int effectRows = orderMapper.updateByPrimaryKeySelective(order1);

            // 没有修改成功
            if (effectRows < 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }

            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.deleteOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;

    }

    /**
     * 暴露的接口：支付成功更新订单信息
     * @param request
     * @return
     */
    @Override
    public PayOrderSuccessResponse updateOrderAfterPaid(PayOrderSuccessRequest request) {
        String orderId = request.getOrderId();
        PayOrderSuccessResponse response = new PayOrderSuccessResponse();

        try {
            // 通过orderId修改order表
            Order order = new Order();
            order.setOrderId(orderId);
            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
            order.setUpdateTime(new Date());
            order.setPaymentTime(new Date());
            int effectRows = orderMapper.updateByPrimaryKeySelective(order);
            if (effectRows < 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }

            // 获取订单中的itemId，需要通过这个id修改库存表
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setStockCount((long) 0);
                stock.setLockCount(-num);
                stock.setItemId(itemId);
                stockMapper.updateStock(stock);
                // TODO: 也没管限购的问题
            }

            // 修改order_item表
            OrderItem orderItem = new OrderItem();
            orderItem.setStatus(OrderConstants.ORDER_ITEM_STATUS_REDUCED);
            int effectRows2 = orderItemMapper.updateByExampleSelective(orderItem, example);
            if (effectRows2 < 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.updateOrderAfterPaid Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public CreateSeckillOrderResponse createPromoOrder(CreateSeckillOrderRequest request) {
        // CreateSeckillOrderResponse response = new CreateSeckillOrderResponse();
        // try {
        //     //创建pipeline对象，orderProcessPipelineFactory需要修改
        //     TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);
        //
        //     //启动pipeline
        //     invoker.start(); //启动流程（pipeline来处理）
        //
        //     //获取处理结果
        //     AbsTransHandlerContext context = invoker.getContext();
        //
        //     //把处理结果转换为response，convertCtx2Respond需要修改
        //     response = (CreateSeckillOrderResponse) context.getConvert().convertCtx2Respond(context);
        //
        //     response.setCode(OrderRetCode.SUCCESS.getCode());
        //     response.setMsg(OrderRetCode.SUCCESS.getMessage());
        //
        // } catch (Exception e) {
        //     log.error("OrderCoreServiceImpl.createPromoOrder Occur Exception :" + e);
        //     ExceptionProcessorUtils.wrapperHandlerException(response, e);
        // }
        //
        // return response;
        return null;
    }

}
